﻿#include "ComBase.h"
#include <QRegularExpression>

#pragma execution_character_set("utf-8")

QMap<ComState, QString> ComBase::mapComStateText = {
    {CS_Invalid, ("<font color=\'red\'>不可用</font>")},
    {CS_Connected, ("<font color=\'green\'>连接成功</font>")},
    {CS_UnConnected, ("<font color=\'yellow\'>断开连接</font>")}
};
QMap<ComClientType, QString> ComBase::mapComClientTypeText = {
    {CCT_Tcp, ("Tcp")},
    {CCT_Serial, ("Serial")},
    {CCT_Udp, ("Udp")}
};

ComBase::ComBase(QObject *parent)
    : QObject{parent}
{
#if QT_VERSION >= 0x060000
// Qt 6 的代码
#else
    // Qt 5 的代码
    qRegisterMetaTypeStreamOperators<SerialComConfig>("SerialComConfig");//注册结构体的操作流,就是重写的输入输出流
    qRegisterMetaTypeStreamOperators<TcpComConfig>("TcpClientConfig");//注册结构体的操作流,就是重写的输入输出流
    qRegisterMetaTypeStreamOperators<UdpComConfig>("UdpClientConfig");//注册结构体的操作流,就是重写的输入输出流
    qRegisterMetaTypeStreamOperators<ComClientConfig>("ComClientConfig");//注册结构体的操作流,就是重写的输入输出流
#endif

    qRegisterMetaType<SerialComConfig>("SerialComConfig");
    qRegisterMetaType<SerialComConfig>("SerialComConfig&");

    qRegisterMetaType<TcpComConfig>("TcpClientConfig");
    qRegisterMetaType<TcpComConfig>("TcpClientConfig&");

    qRegisterMetaType<UdpComConfig>("UdpClientConfig");
    qRegisterMetaType<UdpComConfig>("UdpClientConfig&");

    qRegisterMetaType<ComClientConfig>("ComClientConfig");
    qRegisterMetaType<ComClientConfig>("ComClientConfig&");

    qRegisterMetaType<ComState>("ComState");

    setState(CS_Invalid);
}

void ComBase::setConfig(const ComClientConfig &config)
{
    mConfig = config;
}

void ComBase::onWrite(const QString &data)
{
    if(mConfig.isSendHex){
        QString str = data;
        str.remove(QRegularExpression("\\s"));
        QByteArray sendByte = QByteArray::fromHex(str.toLocal8Bit());
        writeData(sendByte);
    } else {
        writeData(data.toLatin1());
    }
}

void ComBase::onWrite(const QByteArray &data)
{
    writeData(data);
}

void ComBase::onConfigChanged(const ComClientConfig &config)
{
    setConfig(config);
    onInit();
}

void ComBase::setState(const ComState &state)
{
    if(mState == state)
        return;
    mState = state;
    emit sigStateChanged(mState);
}
